package com.daisuxia.back.controller;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.constant.LianLianConstant;
import com.daisuxia.lianlian.entity.LianlianDebitSend;
import com.daisuxia.lianlian.entity.LianlianGrantRecv;
import com.daisuxia.lianlian.entity.LianlianGrantSend;
import com.daisuxia.lianlian.util.DateUtils;
import com.daisuxia.lianlian.util.LLPayUtil;
import com.daisuxia.lianlian.util.RSAUtil;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.dao.IUserDao;
import com.daisuxia.web.pojo.*;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IRepaymentDetailService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.GenerateNo;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.PageConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


/***
 * 还款
 * @author Administrator
 *
 */
@Controller
@RequestMapping("repayment/")
public class RepaymentController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(RepaymentController.class);

	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRepaymentDetailService repaymentDetailService;
    @Autowired
    private IBorrowOrderService borrowOrderService;
	@Autowired
	private IOutOrdersService outOrdersService;


	@RequestMapping("getRepaymentPage")
	public String getUserPage(HttpServletRequest request, Integer[] statuses, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			params.put("statuses", statuses);
			PageConfig<Repayment> pageConfig = repaymentService.findPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getRepaymentPage error", e);
		}
		return "repayment/repaymentList";
	}


	/**
	 * 测试连连代扣
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	/*@RequestMapping("repayTT/{userId}/")
	public void repayT(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer userId) {
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
		UserCardInfo info = userService.findUserBankCard(userId);
		User user = userService.searchByUserid(userId);



		// 签约
		String orderNo = GenerateNo.nextOrdId();
		LianlianGrantSend li = new LianlianGrantSend();
		li.setOid_partner(LianLianConstant.getOidPartner());
		li.setUser_id(user.getId());
		li.setRepayment_no(orderNo);
		li.setRepayment_plan("{\"repaymentPlan\":[{\"date\":\"" + format1.format(new Date()) + "\",\"amount\":\"0.01\"}]}");
		li.setSms_param("{\"contract_type\":\"\u73b0\u91d1\u4fa0\",\"contact_way\":\"021-60498580\"}");
		li.setNo_agree(info.getAgreeno());
		//加签
		String sginOrigin = LLPayUtil.genSignDataByJavaObject(li);
		li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
		String signParam = JSONUtil.beanToJson(li);
		logger.info("LIANLIAN_GRANT_PARAMS:" + signParam);

		String result = HttpUtil.getInstance().postJson(LianLianConstant.getGrantPath(), signParam);
		logger.info("LIANLIAN_GRANT_RETURN:" + result);
//		JSONObject jsonObject = JSONObject.fromObject(result);
		LianlianGrantRecv grantRecv = JSONUtil.jsonToBean(result, LianlianGrantRecv.class);
		sginOrigin = LLPayUtil.genSignDataByJavaObject(grantRecv);
//		System.out.println(RSAUtil.sign("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSS/DiwdCf/aZsxxcacDnooGph3d2JOj5GXWi+" +
//				"q3gznZauZjkNP8SKl3J2liP0O6rU/Y/29+IUe+GTMhMOFJuZm1htAtKiu5ekW0GlBMWxf4FPkYlQ" +
//				"kPE0FtaoMP3gYfh+OwI+fIRrpW3ySn3mScnc6Z700nU/VYrRkfcSCbSnRwIDAQAB", sginOrigin));
//		System.out.println(grantRecv.getSign());


		OutOrders outOrders = new OutOrders();
		outOrders.setUserId(user.getId());
		outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
		outOrders.setOrderNo(orderNo);
		outOrders.setAct(OutOrders.ACT_GRANT);
		outOrders.setReqParams(signParam);
		outOrders.setReturnParams(result);
		outOrders.setStatus(OutOrders.STATUS_SUC);
		outOrdersService.insert(outOrders);
//        {"api_version":"1.0","no_agree":"2016123021071892","oid_partner":"201608101001022519","pay_type":"D","platform":"","repayment_no":"20161230171508109221","repayment_plan":"{\"repaymentPlan\":[{\"date\":\"2016-12-30\",\"amount\":\"0.01\"}]}","sign":"Nwn8hT6+CogezqbbGpdPhXcdZ2RIJDwfnnBRiy7ApJCQtnR3ZbyER4hc1xRvaJcG0qlVgxO302jThx4/sxyE0MGq9rFrfI8oDpYJ6kNDaFiSViOlnkE8YJb+d46pDHY/P1UhDyIuiDZko9oe1en8wdNdV2IGqOCPHlsC/tAvJz4=","sign_type":"RSA","sms_param":"{\"contract_type\":\"贷速侠\",\"contact_way\":\"021-60498580\"}","user_id":"1111"}
//        {"ret_code":"0000","ret_msg":"交易成功","sign_type":"RSA","sign":"Avtv/NU/HaIsX/iRD/REfVIIocOm8zCi9os9Vpx6fAswSHeZFWcsDTy+IdtC5ptT9n2f26rStvoU7eNti/lVFNE/QwTpC42HJVhY/6CPYDm3+B13xrobtPZ2qS+u9Lkil6klWIP+ikDvblXPud03DqhrfH92jKq2WMgEyoweLYQ=","correlationID":"1bba5d74-a13e-4d3f-928c-43c18f6d4911","token":"61C979F1C0112EB0F36A1CCEDF13E8D4","oid_partner":"201608101001022519","no_agree":"2016123021071892","repayment_no":"20161230171508109221"}


		// 代扣
		orderNo = GenerateNo.nextOrdId();
		LianlianDebitSend ll = new LianlianDebitSend();
//        li.setPlatform("180.173.0.188");
		ll.setUser_id(user.getId());
		ll.setNo_order(orderNo);
		ll.setOid_partner(LianLianConstant.getOidPartner());
		ll.setMoney_order("0.01");
		ll.setNotify_url(RequestUtils.getRequestPath(null) + "/repayment/debit-back");
		ll.setValid_order("10");
		ll.setNo_agree(info.getAgreeno());
		ll.setRepayment_no(grantRecv.getRepayment_no());
		String risk = "{'frms_ware_category':'2010','user_info_mercht_userno':'" + userId + "','user_info_bind_phone':'" + user.getUserPhone()
				+ "','user_info_dt_register':'" + format2.format(user.getCreateTime()) + "','user_info_full_name':'" + user.getRealname() + "','user_info_id_no':'" + user.getIdNumber() + "','user_info_identify_type':'1','user_info_identify_state':'1'}";
		ll.setRisk_item(risk);
		//加签
		sginOrigin = LLPayUtil.genSignDataByJavaObject(ll);
		ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
		signParam = JSONUtil.beanToJson(ll);
		logger.info("LIANLIAN_DEBIT_PARAMS:" + signParam);

		result = HttpUtil.getInstance().postJson(LianLianConstant.getDebitPath(), JSONUtil.beanToJson(ll));
		logger.info("LIANLIAN_DEBIT_RETURN:" + result);

		outOrders = new OutOrders();
		outOrders.setUserId(user.getId());
		outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
		outOrders.setOrderNo(orderNo);
		outOrders.setAct(OutOrders.ACT_DEBIT);
		outOrders.setReqParams(signParam);
		outOrders.setReturnParams(result);
		outOrders.setStatus(OutOrders.STATUS_SUC);
		outOrdersService.insert(outOrders);
	}*/

	/**
	 * 还款
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("repay")
	public String repay(HttpServletRequest request, HttpServletResponse response, Model model, RepaymentDetail detail) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		BackUser backUser = this.loginAdminUser(request);
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (null != detail.getAssetRepaymentId()) {
					// 更新的页面跳转
					Repayment repayment = repaymentService.selectByPrimaryKey(detail.getAssetRepaymentId());
					model.addAttribute("remainMoney", (repayment.getRepaymentAmount() - repayment.getRepaymentedAmount()) / 100.00);
					model.addAttribute("assetRepaymentId", detail.getAssetRepaymentId());
				}
				url = "repayment/repay";
			} else {
				if(null == detail.getAssetRepaymentId()){
					erroMsg = "请选择一条还款数据！";
				}
				else{
					Repayment repayment = repaymentService.selectByPrimaryKey(detail.getAssetRepaymentId());
					if(null == repayment){
						erroMsg = "该还款数据无效！";
					}
					else if(!BorrowOrder.STATUS_HKZ.equals(repayment.getStatus()) && !BorrowOrder.STATUS_BFHK.equals(repayment.getStatus()) && !BorrowOrder.STATUS_YYQ.equals(repayment.getStatus()) && !BorrowOrder.STATUS_YHZ.equals(repayment.getStatus())){
						erroMsg = "本条数据不能还款！";
					}
					else{
						detail.setAdminUsername(backUser.getUserAccount());
						detail.setUserId(repayment.getUserId());
						detail.setUpdatedAt(new Date());
						detail.setStatus(RepaymentDetail.STATUS_SUC);
						detail.setAssetOrderId(repayment.getAssetOrderId());
						repaymentDetailService.insertSelective(detail);
						repaymentService.repay(repayment,detail);
						
						
				        // 如果是未逾期的还款，调用提额
				        if (repayment.getLateDay() == 0) {
				            User user = userService.searchByUserid(repayment.getUserId());
							logger.info("repay to Mention Money ing ----------------->");
				            borrowOrderService.addUserLimit(user);
				        }
					}
				}
				SpringUtils.renderDwzResult(response, null == erroMsg, null == erroMsg ? "操作成功！" : erroMsg,
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
		} catch (Exception e) {
			erroMsg = "服务器异常，请稍后重试！";
			SpringUtils.renderDwzResult(response, false, "操作失败,原因："
					+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get(
					"parentId").toString());
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}
}
